package com.blockmeta.bbs.baselibrary.utils;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import androidx.annotation.DrawableRes;
import android.text.TextUtils;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.blankj.utilcode.util.LogUtils;
import com.blockmeta.bbs.baselibrary.R;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.FutureTarget;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ExecutionException;

/**
 * @author AirThor
 * @date 2019/7/2.
 */
public class LoadPicUtil {

    public static void load( String pic, ImageView view) {
        if (TextUtils.isEmpty(pic)){
            return;
        }
        try {
            Glide.with(view.getContext()).load(pic)
                    .placeholder(R.drawable.sys_progressbar_normal).into(view);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 针对im中的gif，包括图片的保存直接从glide disk cache中获取
     * @param pic
     * @param view
     */
    public static void loadWithSourceStrategy( String pic, ImageView view) {
        if (TextUtils.isEmpty(pic)){
            Glide.with(view.getContext()).load(R.drawable.sys_progressbar_normal).into(view);
            return;
        }
        try {
            Glide.with(view.getContext()).load(pic)
                    .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                    .placeholder(R.drawable.sys_progressbar_normal).into(view);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void load( String pic, ImageView view,@DrawableRes int placeholder) {
        if (TextUtils.isEmpty(pic)){
            return;
        }
        try {
            Glide.with(view.getContext()).load(pic).placeholder(placeholder).into(view);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void loadCircle(String pic, ImageView view) {
        if (TextUtils.isEmpty(pic)){
            return;
        }
        try {
            Glide.with(view.getContext()).load(pic).dontAnimate().into(view);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void loadWithPicasso(ImageView imageView, String url) {
        if (TextUtils.isEmpty(url)) {
            imageView.setImageResource(R.drawable.photo_default);
        }else {
            try {
                Picasso.with(imageView.getContext()).load(url).into(imageView);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void loadWithPicasso2(ImageView imageView, String url) {
        if (TextUtils.isEmpty(url)) {
            imageView.setImageResource(R.drawable.photo_default);
        }else {
            try {
                Picasso.with(imageView.getContext()).load(url).into(imageView);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    public static void loadForIm(ImageView imageView,String url){
        loadWithPicassoDefaultAvatar(imageView,url,R.drawable.photo_default);
    }

    public static void loadWithPicassoDefaultAvatar(ImageView imageView, String url, @DrawableRes int defaultAvatar) {
        if (TextUtils.isEmpty(url)) {
            imageView.setImageResource(defaultAvatar);
        }else {
            try {
                Picasso.with(imageView.getContext()).load(url).error(defaultAvatar).into(imageView);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static String getImagePath(String imgUrl, Context context) {
        String path = null;
        FutureTarget<File> future = Glide.with(context)
                .load(imgUrl)
                .downloadOnly(Target.SIZE_ORIGINAL,Target.SIZE_ORIGINAL);
        try {
            File cacheFile = future.get();
            path = cacheFile.getAbsolutePath();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        return path;
    }

    public static void savePictureFromGlide(String oldPath, String ext, Context context) {

        LogUtils.d("author" + "savepic" + oldPath);
        InputStream inStream = null;
        FileOutputStream fs = null;
        String name = System.currentTimeMillis() + "." + ext;
        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + name);
        try {
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { //文件存在时
                inStream = new FileInputStream(oldPath); //读入原文件
                fs = new FileOutputStream(file.getAbsolutePath());
                byte[] buffer = new byte[1024];
                while (inStream.read(buffer) > 0) {
                    fs.write(buffer);
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if(inStream != null){
                    inStream.close();
                }
                if(fs != null){
                    fs.close();
                }
                Intent intentBroadcast = new Intent(
                        Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                intentBroadcast.setData(Uri.fromFile(new File(file.getAbsolutePath())));
                context.sendBroadcast(intentBroadcast);

                ToastUtil.show(context,"图片已保存");
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

    public static void loadPicWithGlideRatio(String path,ImageView imageView){
//        if (TextUtils.isEmpty(path)){
//            return;
//        }
//        try {
//            Glide.with(imageView.getContext()).load(path)
//                    .listener(new RequestListener<String, GlideDrawable>() {
//                        @Override
//                        public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
//                            return false;
//                        }
//
//                        @Override
//                        public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
//                            if (imageView.getScaleType() != ImageView.ScaleType.FIT_XY) {
//                                imageView.setScaleType(ImageView.ScaleType.FIT_XY);
//                            }
//                            ViewGroup.LayoutParams params = imageView.getLayoutParams();
//                            int vw = imageView.getWidth() - imageView.getPaddingLeft() - imageView.getPaddingRight();
//                            float scale = (float) resource.getIntrinsicWidth()/(float) resource.getIntrinsicHeight();
//                            int vh = (int) ((float)vw/scale);
//                            params.height = vh + imageView.getPaddingTop() + imageView.getPaddingBottom();
//                            imageView.setLayoutParams(params);
//                            return false;
//                        }
//                    })
//                    .placeholder(R.drawable.yoona)
//                    .into(imageView);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }
}
